package com.jishuo.base.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.Key;
import java.security.SecureRandom;

/**
 * AES加解密
 */
public class AESUtil {
    private static final String ALGORITHM = "AES";
    private static final BASE64Decoder BASE64_DECODER = new BASE64Decoder();
    private static final BASE64Encoder BASE64_ENCODER = new BASE64Encoder();

    /**
     * 解密
     * @param str 密文
     * @param key 密钥
     * @return 原文
     * @throws Exception
     */
    public static String decode(String str, String key) {
        try {
            // 密文base64解码
            byte[] bt1 = BASE64_DECODER.decodeBuffer(str);
            // 解密
            byte[] bt2 = decrypt(bt1, key);
            // 再次base64解码
            return new String(BASE64_DECODER.decodeBuffer(new String(bt2)));
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    private static byte[] decrypt(byte[] data, String key) throws Exception {
        SecretKey k = genKey(key.getBytes());
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, k);
        return cipher.doFinal(data);
    }

    /**
     * 加密
     * @param str 原文
     * @param key 密钥
     * @return 密文
     * @throws Exception
     */
    public static String encode(String str, String key) {

        try {
            // 原文进行base64编码
            String code = BASE64_ENCODER.encode(str.getBytes());
            // 加密
            byte[] bt = encrypt(code.getBytes(), key);
            // 再次base64编码
            return BASE64_ENCODER.encode(bt);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }

    }

    private static byte[] encrypt(byte[] data, String key) throws Exception {
        Key ky = genKey(key.getBytes());
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, ky);
        return cipher.doFinal(data);
    }

    private static SecretKey genKey(byte[] key) throws Exception {
        KeyGenerator keyG = KeyGenerator.getInstance("AES");
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(key);
        keyG.init(128, secureRandom);
        return keyG.generateKey();
    }

//    public static void main(String[] args) throws Exception {
//        String key = "adfasdfasfdasfdsfsa";
//        String str = "abc123总务";
//        String enc = AESUtil.encode(str, key);
//        System.out.println(enc);
//        System.out.println(AESUtil.decode(enc, key));
//    }
}
